﻿#region imports

using System;
using System.Globalization;
using System.Net;
using System.Web;
using Codeplex.ODataTFS.Model.Entities;
using Microsoft.TeamFoundation.Framework.Client;
using Microsoft.TeamFoundation.Framework.Common;

#endregion

namespace Codeplex.ODataTFS.Model.Serialization
{
	public class TFSUserProxy : TFSBaseProxy
	{
		public TFSUserProxy(Uri uri, ICredentials credentials)
			: base(uri, credentials)
		{
		}

		public User GetUserByUserName(string userName)
		{
			var key = string.Format(CultureInfo.InvariantCulture, "TFSUserProxy.GetUserByEmail_{0}", userName);

			if (Cache[key] == null)
			{
				Cache[key] = RequestUserByUserName(userName);
			}

			return (User) Cache[key];
		}

		private User RequestUserByUserName(string userName)
		{
			if (string.IsNullOrEmpty(userName))
			{
				throw new ArgumentNullException("userName");
			}
			if (userName.Contains(":"))
			{
				userName = userName.Replace(":", "\\");
			}

			IIdentityManagementService gss = (IIdentityManagementService) TfsConnection.GetService(typeof (IIdentityManagementService));
			TeamFoundationIdentity identity = gss.ReadIdentity(IdentitySearchFactor.General, userName, MembershipQuery.Expanded, ReadIdentityOptions.ExtendedProperties);

			if (identity == null)
			{
				throw new System.Data.Services.DataServiceException(404, "Not Found", "User lookup failed", "en-US", null);
			}

			return identity.ToModel(userName);
		}
	}
}
